<template>
  <div ref="container" id="container"></div>
</template>

<script setup>
import * as THREE from "three";
import { onMounted, ref } from "vue";

const container = ref(null);
let scene, camera, renderer;

onMounted(() => {
  // 初始化渲染
  const width = window.innerWidth;
  const height = window.innerHeight;

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
  renderer = new THREE.WebGLRenderer({ alpha: true });

  renderer.setSize(width, height);
  container.value.appendChild(renderer.domElement);

  // 自定义顶点数据
  const vertices = [
    -1,
    -1,
    -1 / Math.sqrt(3), // 底面三角形的左下角顶点
    1,
    -1,
    -1 / Math.sqrt(3), // 底面三角形的右下角顶点
    0,
    1,
    -1 / (2 * Math.sqrt(3)), // 顶部顶点
    0,
    0,
    1 / (2 * Math.sqrt(3)), // 底面中心顶点
  ];

  // 如果要按照逆时针顺序连接顶点，可以定义一个顶点索引数组
  const indices = [0, 1, 2, 0, 2, 3, 1, 2, 3];

  // 创建BufferGeometry对象
  const geometry = new THREE.BufferGeometry();

  // 设置顶点属性
  const positionAttribute = new THREE.Float32BufferAttribute(vertices, 3);
  geometry.setAttribute("position", positionAttribute);

  // 设置顶点索引
  geometry.setIndex(indices);

  const material = new THREE.MeshBasicMaterial({
    color: 0x00ff00,
    wireframe: true,
  });
  const cube = new THREE.Mesh(geometry, material);

  // 添加到场景中
  scene.add(cube);

  // 设置相机的位置和朝向
  camera.position.z = 5;

  // 动画循环
  function animate() {
    requestAnimationFrame(animate);

    // 在这里进行模型的旋转、平移等操作
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
  }

  animate();
});
</script>

<style scoped>
#container {
  width: 30%;
  height: 30%;
}
</style>
